package com.sdk;

/*
 * Copyright 2017 JessYan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;

import com.com.unionpay.constant.Config;
import com.com.unionpay.constant.Constant;
import com.com.unionpay.utils.DeviceUtils;
import com.sdk.widget.FreeImageView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;


/**
 * ================================================
 * {@link Application.ActivityLifecycleCallbacks} 默认实现类
 * 通过 {@link SpeechDealService} 管理 {@link Activity}
 *
 * @see <a href="http://www.jianshu.com/p/75a5c24174b2">ActivityLifecycleCallbacks 分析文章</a>
 * Created by JessYan on 21/02/2017 14:23
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * ================================================
 */
public class ActivityLifecycle implements Application.ActivityLifecycleCallbacks {

    public static final long CHECK_DELAY = 500;
    private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
    private static ActivityLifecycle sActivityLifecycle;
    AppManager mAppManager;

    private boolean foreground = false, paused = true;
    private Handler handler = new Handler();
    private Runnable check;
    private View mContentRoot;
    private final DoubleKeyValueMap mDoubleKeyValueMap;


    public static ActivityLifecycle getInstance() {
        if (sActivityLifecycle == null) {
            synchronized (AppManager.class) {
                if (sActivityLifecycle == null) {
                    sActivityLifecycle = new ActivityLifecycle();
                }
            }
        }
        return sActivityLifecycle;
    }

    public ActivityLifecycle() {
        LogUtils.e("ActivityLifecycleCreat");
        mAppManager = AppManager.getInstance();
        mDoubleKeyValueMap = DoubleKeyValueMap.getInstance();
    }


    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        //如果 intent 包含了此字段,并且为 true 说明不加入到 list 进行统一管理
        boolean isNotAdd = false;
//        if (activity.getIntent() != null)
//            isNotAdd = activity.getIntent().getBooleanExtra(AppManager.IS_NOT_ADD_ACTIVITY_LIST, false);
        if (!(activity instanceof IActivity))
            return;
        isNotAdd = ((IActivity) activity).getSpeechActiveMode() == null;

        if (!isNotAdd)
            mAppManager.addActivity(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (activity instanceof IActivity &&
                ((IActivity) activity).showEasyTouch()) {
            initEasyTouch(activity);
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {
        mAppManager.setCurrentActivity(activity);
        showEasyTouch(activity);
        paused = false;

        boolean wasBackground = !foreground;
        foreground = true;
        if (listeners.size() != 0) {
            listeners.get(0).onActivityResume( activity);
        }
        if (check != null)
            handler.removeCallbacks(check);
        if (wasBackground) {
            //LogUtils.e("went foreground");
            for (Listener l : listeners) {
                try {
                    if (!Config.IS_SPEECHSERVICE_ALIVE) {
                        Intent mIntelligentVoiceService = new Intent(activity, SpeechDealService.class);
                        activity.startService(mIntelligentVoiceService);
                    }
                    l.onBecameForeground();
                } catch (Exception exc) {
                    LogUtils.e("Listener threw exception!", exc.toString());
                }
            }
        } else {
            // LogUtils.e("still foreground");
        }
    }


    @Override
    public void onActivityPaused(Activity activity) {
        paused = true;
        saveEasyTouchXY(activity);
        if (check != null)
            handler.removeCallbacks(check);
        handler.postDelayed(check = new Runnable() {
            @Override
            public void run() {
                if (foreground && paused) {
                    foreground = false;
                    LogUtils.e("went background");
                    for (Listener l : listeners) {
                        try {
                            l.onBecameBackground();
                        } catch (Exception exc) {
                            LogUtils.e("Listener threw exception!" + exc.toString());
                        }
                    }
                } else {
                    LogUtils.e("still foreground");
                }
            }
        }, CHECK_DELAY);
    }


    @Override
    public void onActivityStopped(Activity activity) {
        FreeImageView easyTouchFimgv = getImageView(activity);
        if (easyTouchFimgv != null) {
            easyTouchFimgv.setVisibility(View.GONE);
        }
        if (mAppManager.getCurrentActivity() == activity) {
            mAppManager.setCurrentActivity(null);
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        mAppManager.removeActivity(activity);
        mDoubleKeyValueMap.remove(Constant.KEY_DOUBLEKEYVALUEMAP, activity.getClass().getName());

    }

    public interface Listener {
        void onBecameForeground();

        void onBecameBackground();

        void onActivityResume(Activity activity);
    }

    public void addListener(Listener listener) {
        listeners.add(listener);
    }

    public void removeListener(Listener listener) {
        listeners.remove(listener);
    }

    private void initEasyTouch(Activity activity) {
        mContentRoot = View.inflate(activity,
                activity.getResources().getIdentifier("view_easy_touch", "layout", activity.getPackageName()), null);
        FreeImageView easyTouchFimgv = getImageView(activity);
        if (mContentRoot != null && easyTouchFimgv == null) {
            FreeImageView mEasyTouchFimgv = mContentRoot.findViewWithTag("easytouch_fimgv");
            FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            activity.addContentView(mContentRoot, param);
            mDoubleKeyValueMap.put(Constant.KEY_DOUBLEKEYVALUEMAP, activity.getClass().getName(), mEasyTouchFimgv);
        }

    }

    /**
     * {@link Activity#onResume()}的时候 从{@link android.content.SharedPreferences}中获取
     * 上一次{@link FreeImageView}显示的位置坐标，如果是第一次显示初始化{@link FreeImageView}位置
     * @param activity
     */
    private void showEasyTouch(Activity activity) {
        FreeImageView easyTouchFimgv = getImageView(activity);
        if (easyTouchFimgv != null) {
            easyTouchFimgv.setVisibility(View.VISIBLE);
            int oldx = activity.getApplicationContext().getSharedPreferences(Constant.KEY_SHARED_PREFERENCES_NAME,
                    Activity.MODE_PRIVATE)
                    .getInt(Constant.KEY_SP_EASYTOUCH_X, (int) (DeviceUtils.getScreenWidth(activity) - (int)DeviceUtils.dpToPixel(activity,48)));
            int oldy = activity.getApplicationContext().getSharedPreferences(Constant.KEY_SHARED_PREFERENCES_NAME,
                    Activity.MODE_PRIVATE)
                    .getInt(Constant.KEY_SP_EASYTOUCH_Y, (int) (DeviceUtils.getScreenWidth(activity) / 2 + DeviceUtils.getStatuBarHeight(activity)));
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams((int)DeviceUtils.dpToPixel(activity,48), (int)DeviceUtils.dpToPixel(activity,48));
            lp.setMargins(oldx, oldy, 0, 0);
            easyTouchFimgv.setLayoutParams(lp);
            easyTouchFimgv.setOnListener(new FreeImageView.OnListener() {
                @Override
                public void onClick(View view) {
                    EventBus.getDefault().post(new MessageEvent(Constant.EVENT_CLICK_ACTIVE, ActiveMode.CLICK));
                }
            });
        }
    }

    /**
     *
     * 在{@link Activity} finish前保存{@link FreeImageView}的当前位置坐标
     *
     */
    public void saveEasyTouchXY(Activity activity) {
        FreeImageView easyTouchFimgv = getImageView(activity);
        if (null != easyTouchFimgv && easyTouchFimgv.lastY > -1) {
            activity.getApplicationContext().getSharedPreferences(Constant.KEY_SHARED_PREFERENCES_NAME,
                    Activity.MODE_PRIVATE)
                    .edit().putInt(Constant.KEY_SP_EASYTOUCH_X, easyTouchFimgv.lastX).commit();
LogUtils.i("easytouchLastY="+easyTouchFimgv.lastX);
            activity.getApplicationContext().getSharedPreferences(Constant.KEY_SHARED_PREFERENCES_NAME,
                    Activity.MODE_PRIVATE)
                    .edit().putInt(Constant.KEY_SP_EASYTOUCH_Y, easyTouchFimgv.lastY).commit();

        }
    }

    public FreeImageView getImageView(Activity activity) {
        FreeImageView easyTouchFimgv = (FreeImageView) mDoubleKeyValueMap.get(Constant.KEY_DOUBLEKEYVALUEMAP, activity.getClass().getName());
        return easyTouchFimgv;
    }

}
